<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 
      1. 演示官网的搜索案例
     -->

    <div id="app">
      <p>
        Ask a yes/no question:
        <input v-model="question" />
      </p>
      <p>{{ answer }}</p>
      <img :src="image" alt="" />
    </div>

    <script src="../lib/vue-3.js"></script>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            question: "",
            answer: "请输入问题",
            image: "", // 图片URL地址
          };
        },
        watch: {
          // 每当 question 改变时，这个函数就会执行
          question(newQuestion, oldQuestion) {
            if (newQuestion.includes("?")) {
              this.getAnswer();
            }
          },
        },
        methods: {
          async getAnswer() {
            // 调用接口之前，先将 答案设置未 "Thinking"
            this.answer = "Thinking...";
            try {
              // fetch(请求地址) 默认发送 get 请求
              const res = await fetch("https://yesno.wtf/api").then(
                (response) => response.json()
              );

              console.log("res", res);
              // 将接口响应数据的 answer 字段赋值给 answer
              this.answer = res.answer;
              this.image = res.image;
            } catch (error) {
              this.answer = "Error! Could not reach the API. " + error;
            }
          },
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
